package service;

import cn.hutool.db.Session;
import utils.Constant;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@WebListener
public class SessionListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        if (Constant.LOGIN_SESSION.equals(event.getName())){
            HttpSession session = event.getSession();
            String id = session.getId();
            ServletContext servletContext = session.getServletContext();
            ConcurrentHashMap<String,HttpSession> sessionConcurrentHashMap = (ConcurrentHashMap<String,HttpSession>)
                    servletContext.getAttribute(Constant.ONLINE_USER);
            sessionConcurrentHashMap.put(id,session);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (Constant.LOGIN_SESSION.equals(event.getName())){
            HttpSession session = event.getSession();
            String id = session.getId();
            ServletContext servletContext = session.getServletContext();
            ConcurrentHashMap<String, HttpSession> map = (ConcurrentHashMap<String, HttpSession>)
                    servletContext.getAttribute(Constant.ONLINE_USER);
            map.remove(id);

        }
    }
}
